import 'package:flutter/cupertino.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';

import '../../../../http/api.dart';
import '../../../../http/http_utils.dart';
import '../../../../res/w_colors.dart';
import '../../../../res/w_constant.dart';
import '../../../../utils/common_req_utils.dart';
import '../../../../utils/common_utils.dart';
import '../../../../utils/router_helper.dart';
import '../../../../widget/common_attachment.dart';
import '../../../../widget/label_item.dart';
import '../../../../widget/w_text.dart';
import '../../../../widget/w_toast.dart';
import '../../model/leads_follow_info.dart';

class LeadsAssistancePage extends StatefulWidget {
  final Map leadsData;

  const LeadsAssistancePage({super.key, required this.leadsData});

  @override
  BaseState<LeadsAssistancePage> createState() => _LeadsAssistancePageState();
}

class _LeadsAssistancePageState extends BaseState<LeadsAssistancePage> {
  LeadsFollowInfo leadsFollowInfo = LeadsFollowInfo();
  late ScrollController _controller;
  List<Map> _attachmentImages = [];


  GlobalKey<CommonAttachmentState>? picKey;

  @override
  void initState() {
    super.initState();
    _controller = ScrollController();
    picKey = GlobalKey(debugLabel: "picKey");
    _controller.addListener(() {
      if (_controller.position.pixels >= _controller.position.maxScrollExtent) {
        picKey!.currentState?.refreshImageList( _attachmentImages);
      }
    });
    leadsFollowInfo.clueId = widget.leadsData["existClueId"];
    leadsFollowInfo.followResult = 19101001;
    leadsFollowInfo.level = widget.leadsData["level"];
    leadsFollowInfo.nextFollowTime = widget.leadsData["nextFollowDate"];
    leadsFollowInfo.isAppointDrive = 10011002;
  }

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "共同跟进",
        rightWidget: GestureDetector(
          onTap: () {
            CommonUtils.throttle(saveFollowUpInfo);
          },
          child: WText(
            "保存",
            style: TextStyle(
              color: WColors.primaryColor,
              fontSize: 14.px,
            ),
          ),
        ),
        child: ListView(
            padding: EdgeInsets.zero,
            controller: _controller,
            children: [
              LabelItem(
                label: "跟进方式",
                isMust: true,
                labelType: LabelType.DROW_DOWN,
                onSelected: (value) {
                  setState(() {
                    leadsFollowInfo.followMethod =
                        value == null ? null : int.parse(value);
                  });
                },
                dataList: WConstant.followUpWayList,
                value: leadsFollowInfo.followMethod.toString(),
              ),
              const LabelItem(
                label: "跟进结果",
                value: "继续",
              ),
              LabelItem(
                label: "意向级别",
                value: CommonReqUtils.exchangeCodeToName(
                    CommonReqUtils.intentRange, leadsFollowInfo.level),
              ),
              LabelItem(
                labelType: LabelType.TEXTAREA,
                maxTextLength: 1000,
                isMust: true,
                label: "跟进记录",
                onChanged: (text) {
                  setState(() {
                    leadsFollowInfo.followRemark = text;
                  });
                },
              ),
              LabelItem(
                  label: "下次跟进时间:",
                  value: leadsFollowInfo.nextFollowTime.toString()),
              const LabelItem(
                label: "邀约试驾",
                value: "否",
              ),
              CommonAttachment(
                key: picKey,
                onSelected: (values, images) {
                  _attachmentImages = images;
                  List<Map<String, dynamic>> picList = [];
                  if (values.isEmpty) {
                    leadsFollowInfo.filesList = null;
                  } else {
                    for (int i = 0; i < values.length; i++) {
                      Map<String, dynamic> fileMap = {
                        "fileUploadInfoId": values[i],
                        "url": null
                      };
                      picList.add(fileMap);
                    }
                    leadsFollowInfo.filesList = picList;
                  }
                },
              )
            ]));
  }

  saveFollowUpInfo() {
    if (LeadsFollowInfo.check(leadsFollowInfo, true)) {
      showLoading();
      Map params = leadsFollowInfo.toJson();
      params["isAssistance"] = true;
      HttpUtils().post(Api.saveFollowInfo, data: params).then((value) {
        hideLoading();
        if (value.resultCode == 200) {
          Toast.toast("保存成功");
          RouteHelper.maybePop(context, true);
        } else {
          Toast.toast("${value.errMsg}");
        }
      });
    }
  }
}
